﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;

namespace Util
{
    public class ResLink
    {
        private static string CSS_KEY = "CssLink";
        private static string JS_KEY = "JsLink";

        public static void AddCss(string url)
        {
            Add(CSS_KEY, url);
        }

        public static void AddJs(string url)
        {
            Add(JS_KEY, url);
        }

        private static void Add(string key, string url)
        {
            var list = (List<string>)HttpContext.Current.Items[key];
            if (list == null)
                HttpContext.Current.Items[key] = list = new List<string>();
            if (list.Contains(url) == false) list.Add(url);
        }

        public static MvcHtmlString Render()
        {
            var result = new StringBuilder();
            RenderCss(result);
            RenderJs(result);
            return MvcHtmlString.Create(result.ToString());
        }

        private static void RenderCss(StringBuilder result)
        {
            var list = (List<string>)HttpContext.Current.Items[CSS_KEY];
            if (list == null) return;

            foreach (var url in list) {
                result.Append("<link href='");
                result.Append(System.Web.VirtualPathUtility.ToAbsolute(url));
                result.Append("' rel='stylesheet' media='screen'>");
            }
        }


        private static void RenderJs(StringBuilder result)
        {
            var list = (List<string>)HttpContext.Current.Items[JS_KEY];
            if (list == null) return;

            foreach (var url in list) {
                result.Append(" <script src='");
                result.Append(System.Web.VirtualPathUtility.ToAbsolute(url));
                result.Append("' type='text/javascript' charset='utf-8'></script>");
            }
        }
    }
}